<template>
  <k-form-modal
    width="small"
    title="编辑"
    v-bind="formModalState"
    v-on="formModalEvent"
  >
    <el-form-item label="发放数量" prop="num">
      <el-input-number
        v-model="state.model.num"
        controls-position="right"
        placeholder="发放数量"
        clearable
        :min="state.model.num"
        style="width: 100%"
        @change="onChangeNum"
      />
    </el-form-item>
    <el-form-item v-if="showNumTips">修改数量不得小于原设置的数量</el-form-item>
    <el-form-item label="失效时间" prop="invalid_time">
      <el-date-picker
        v-model="state.model.invalid_time"
        type="datetime"
        format="YYYY-MM-DD HH:mm:ss"
        placeholder="失效时间"
        style="width: 100%"
      />
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang='ts'>
import dayjs from 'dayjs';
import { ref } from 'vue';
import { useFormModal, baseConfirm } from '@crud/index';
import { updateChannel } from '@/api/crm-agency/dyj/lecturer';
import { ElMessage } from 'element-plus';
defineOptions({
  name: 'ExchangeListEditModal'
});
const emits = defineEmits(['success']);
const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  model: {
    num: '',
    channel_id: undefined,
    agent_id: undefined,
    invalid_time: ''
  },
  rules: {
  },
  onShow: (mode = 0, data: any) => {
    if (data) {
      state.model = {
        invalid_time: data.end_time ? data.end_time * 1000 : '',
        num: data.total,
        total: data.total,
        channel_id: data.batch_id,
        agent_id: data.agent_id
      };
    }
  },
  onSubmit: async (model: any, mode = 0) => {
    if (mode === 1) {
      await baseConfirm({ title: '编辑', message: '确定要更改当前设置？' });
      const res = await updateChannel({ ...model, total: undefined, invalid_time: dayjs(model.invalid_time).unix() });
      if (!res.err) {
        ElMessage.success('修改成功');
        emits('success');
      }
      return res;
    }

  }
});
const showNumTips = ref(false);
const onChangeNum= (value: number) => {
  if (value >= state.model.total) {
    showNumTips.value = false;
  } else {
    showNumTips.value = true;
    state.model.num = state.model.total;
  }
};
defineExpose({
  show: methods.show
});
</script>
